package com.ttt.radioapp_core.helpers;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class AsyncLoadImage extends AsyncTask<String, Integer, Object> {
	private static final String TAG = "AsyncLoadImage ";
	private ImageView iv;
	private HttpURLConnection connection;
	private InputStream is;
	private Bitmap bitmap;

	public AsyncLoadImage(ImageView mImageView) {
		iv = mImageView;
	}

	@Override
	protected Object doInBackground(String... params) {
		URL url;
		try {
			if (params.length == 1) {
				url = new URL(params[0]);
				connection = (HttpURLConnection) url.openConnection();
				connection.setDoInput(true);
				connection.connect();
				is = connection.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (connection != null) {
					connection.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if (null != result) {
			iv.setImageBitmap((Bitmap) result);
			iv.setVisibility(View.VISIBLE);
			Log.i(TAG, "image download ok!!!");
		} else {
			// iv.setBackgroundResource(R.drawable.shuben1);
			iv.setVisibility(View.GONE);
			Log.i(TAG, "image download false!!!");
		}
	}
}